package com.qianchang.microfinance.view.mine.loan;

import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;

import com.dm.library.http.DMOKHttpUtils;
import com.dm.library.http.HttpParams;
import com.dm.library.http.base.JsonResult;
import com.dm.library.http.callback.RequestCallBack;
import com.dm.library.utils.FormatUtil;
import com.dm.library.utils.ToastUtil;
import com.dm.library.widgets.element.DTextView;
import com.qianchang.microfinance.R;
import com.qianchang.microfinance.bean.FindUserBasicInfoBean;
import com.qianchang.microfinance.bean.MineUserInfo;
import com.qianchang.microfinance.bean.RepayPlanAfterParams;
import com.qianchang.microfinance.bean.RepaymentPlanAfterBean;
import com.qianchang.microfinance.bean.RepaymentPlanBean;
import com.qianchang.microfinance.bean.UserLoginInfo;
import com.qianchang.microfinance.global.DMApplication;
import com.qianchang.microfinance.utils.DMConstant;
import com.qianchang.microfinance.utils.RepayModeUtil;
import com.qianchang.microfinance.view.base.BaseActivity;
import com.qianchang.microfinance.view.base.DmBaseActivity;
import com.qianchang.microfinance.view.base.EmptyLayout;
import com.qianchang.microfinance.view.base.RecyclerRefreshLayout;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * 还款计划
 */
public class RepayPlanActivity extends BaseActivity {


    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.error_layout)
    EmptyLayout errorLayout;
    @BindView(R.id.refreshLayout)
    RecyclerRefreshLayout refreshLayout;
    @BindView(R.id.tv_total)
    DTextView tvTotal;
    @BindView(R.id.tv_daily_rate_and_all_interest)
    DTextView tvDailyRateAndAllInterest;
    @BindView(R.id.tv_total_interest_id)
    DTextView tvTotalinerest;
    @BindView(R.id.tv_audit_fee_id)
    DTextView tvAuditFee;
    @BindView(R.id.tv_actual_arrival_id)
    DTextView tvActualArrival;
    private String deadline;
    private String repaymentType;
    private String rate;
    private String serviceFeeSetting;

    private boolean isLoanBefore;// true 是贷前
    private double loanAmount;
    private String projectId;
    private RepaymentPlanAdapter adapter;
    private List mList = new ArrayList();
    private String strRepayMode;//贷后传来的 还款方式
    private String strInterestRate;
    private String repayModeId;
    private RepayPlanAfterParams planAfterParams;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_repay_plan);
        ButterKnife.bind(this);
        initView();
        initData();
        updateStatus();
    }


    @Override
    protected void initView() {
        super.initView();


        setTitleName(getString(R.string.Label_reply_plan));
        initList();
        Bundle bundle = getBundle();
        //生成
        repaymentType = bundle.getString("repaymentType");
        deadline = bundle.getString("deadline");//借款期限
        rate = bundle.getString("reta");//利率（月）
        serviceFeeSetting = bundle.getString("serviceFeeSetting");// 是否是固定金额
        loanAmount = bundle.getDouble("applyAmount");//借款金额
        double allInterestRate = bundle.getDouble("allInterestRate");//总利息
        String strRate = bundle.getString("strRate");
        if (repaymentType != null || deadline != null || rate != null || serviceFeeSetting != null) {
            //生成还款计划
            isLoanBefore = true;
            tvTotal.setText(FormatUtil.numKbPointFormat(loanAmount + allInterestRate));
            tvDailyRateAndAllInterest.setText(strRate + "," + getString(R.string.total_interest) + FormatUtil.numKbPointFormat(allInterestRate));

            tvTotalinerest.setText(FormatUtil.numKbPointFormat(allInterestRate));    //总利息
            double tvaduit = (loanAmount * 0.18);
            double tvActualArri = (loanAmount - tvaduit);
            tvAuditFee.setText(FormatUtil.numKbPointFormat(tvaduit));                           //快速审核费
            tvActualArrival.setText(FormatUtil.numKbPointFormat(tvActualArri));                 //实时到帐

            getPlanBefore();
        } else {
            //查询
//                projectId,月利率,还款类型id
            planAfterParams = (RepayPlanAfterParams) bundle.getSerializable(RepayPlanAfterParams.class.getName());
            if (planAfterParams != null && planAfterParams.getProjectId() != null) {
                isLoanBefore = false;
                repayModeId = planAfterParams.getRepayModeId();
                strRepayMode = RepayModeUtil.getRepayMode(repayModeId, this);
                projectId = planAfterParams.getProjectId();
                getPlanAfter();
            } else {
                showDataError();
            }
        }
    }

    @Override
    protected void initData() {
        super.initData();
        refreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                if (isLoanBefore) {
                    getPlanBefore();
                } else {
                    getPlanAfter();
                }
            }
        });
    }

    private void initList() {
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        adapter = new RepaymentPlanAdapter(RepayPlanActivity.this, mList, R.layout.adapter_repay_plan);
        recyclerView.setAdapter(adapter);
    }

    private void getPlanAfter() {
        HttpParams params = new HttpParams();
        params.put("projectId", projectId);
        show();
        DMOKHttpUtils.getInstance().post(this, DMConstant.ApiURL.QUERY_PLAN_LIST, params, new RequestCallBack<List<RepaymentPlanAfterBean>>() {
            @Override
            public void onSuccess(JsonResult<List<RepaymentPlanAfterBean>> response) {
                dismiss();
                refreshLayout.setRefreshing(false);
                if (DMConstant.Code.CODE_OK.equals(response.getCode())) {
                    if (response.getObject() != null) {
                        refresh(response.getObject());
                    }
                } else {
                    ToastUtil.getInstant().show(RepayPlanActivity.this, response.getDescription());
                }
            }

            @Override
            public void onFailure(String msg) {
                dismiss();
                refreshLayout.setRefreshing(false);
                ToastUtil.getInstant().show(RepayPlanActivity.this, msg);
            }

            @Override
            public void onConnectFailure(String msg) {

            }
        });
    }

    private void getPlanBefore() {
        HttpParams params = new HttpParams();
        params.put("applyAmount", loanAmount);
        params.put("repaymentType", repaymentType);
        params.put("deadline", deadline);
        params.put("reta", rate);
        params.put("serviceFeeSetting", "1");//
        show();
        DMOKHttpUtils.getInstance().post(this, DMConstant.ApiURL.REPAYMENT_PLAN_BEFORE, params, new RequestCallBack<RepaymentPlanBean>() {
            @Override
            public void onSuccess(JsonResult<RepaymentPlanBean> response) {
                dismiss();
                refreshLayout.setRefreshing(false);
                if (DMConstant.Code.CODE_OK.equals(response.getCode())) {
                    RepaymentPlanBean bean = response.getObject();
                    if (bean.getPlanList() != null) {
                        refresh(bean.getPlanList());
                    }
                } else {
                    ToastUtil.getInstant().show(RepayPlanActivity.this, response.getDescription());
                }

            }

            @Override
            public void onFailure(String msg) {
                dismiss();
                refreshLayout.setRefreshing(false);
                ToastUtil.getInstant().show(RepayPlanActivity.this, msg);
            }

            @Override
            public void onConnectFailure(String msg) {

            }
        });
    }

    private void refresh(List planList) {
        if (planList == null) return;
        mList.clear();
        mList.addAll(planList);
        adapter.notifyDataSetChanged();
        if (!isLoanBefore) {
            double totalAmount = 0;
            double totalInterest = 0;//zonglixi
            for (int i = 0; i < planList.size(); i++) {
                if (planList.get(i) instanceof RepaymentPlanAfterBean) {
                    RepaymentPlanAfterBean bean = (RepaymentPlanAfterBean) planList.get(i);
                    if (bean != null) {
                        totalAmount += bean.getInterest() + bean.getPrincipal() + bean.getOverdue();
                        totalInterest += bean.getInterest();
                    }
                }
            }
            tvTotal.setText(FormatUtil.numKbPointFormat(totalAmount));
            //日利率0.05%，总利息￥5,000
            try {
                double d = Double.valueOf(planAfterParams.getMonthInterestRate());
                double dPerDay;
                if ("0".equals(repayModeId)) {//0:表示日利率//1,2,3 都是月利率 参考RepayModeUtil.getRepayMode()、、、、unit（0：天 1:月）
                    BigDecimal bg = new BigDecimal(d * 100 / 30);
                    dPerDay = bg.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
                    strInterestRate = getString(R.string.Label_daily_interest_rate) + dPerDay + "%";
                } else {//月
                    BigDecimal bg = new BigDecimal(d * 100);
                    dPerDay = bg.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
                    strInterestRate = getString(R.string.Label_monthly_interest_rate) + dPerDay + "%";
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            tvDailyRateAndAllInterest.setText(strInterestRate + ", " + getString(R.string.total_interest) + FormatUtil.numKbPointFormat(totalInterest));

            tvTotalinerest.setText(FormatUtil.numKbPointFormat(totalInterest));    //总利息
            double tvaduit = (loanAmount * 0.18);
            double tvActualArri = (loanAmount - tvaduit);
            tvAuditFee.setText(FormatUtil.numKbPointFormat(tvaduit));                           //快速审核费
            tvActualArrival.setText(FormatUtil.numKbPointFormat(tvActualArri));                 //实时到帐


        }
    }


    private JsonResult<FindUserBasicInfoBean> mResponse;
    private FindUserBasicInfoBean basicInfoBean;
    private void updateStatus() {
        show();
        HttpParams params = new HttpParams();
        DMOKHttpUtils.getInstance().post(RepayPlanActivity.this, DMConstant.ApiURL.FIND_USER_BASIC_INFO, params, new RequestCallBack<FindUserBasicInfoBean>() {
            @Override
            public void onSuccess(JsonResult<FindUserBasicInfoBean> response) {
                dismiss();
                mResponse = response;
                if (DMConstant.Code.CODE_OK.equals(response.getCode())) {
                    basicInfoBean = response.getObject();
                    if (basicInfoBean != null){
                        String userName = basicInfoBean.getRealName() + "的";
                        setTitleName(userName + getString(R.string.Label_reply_plan));
                    }
                } else {
                    if (!"300001".equals(response.getCode())) {
                        if (!"300084".equals(response.getCode())) {
                            ToastUtil.getInstant().show(RepayPlanActivity.this, response.getDescription());
                        }
                    }
                }
            }

            @Override
            public void onFailure(String msg) {
                dismiss();
                ToastUtil.getInstant().show(RepayPlanActivity.this, msg);
            }

            @Override
            public void onConnectFailure(String msg) {
            }

        });
    }



}